package com.example.weatherapp233;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import com.example.weatherapp233.gson.NowWeather;
import com.example.weatherapp233.util.HttpUtil;
import com.google.gson.Gson;

import java.io.IOException;

import io.reactivex.rxjava3.annotations.Nullable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherService extends Service {
    private static final String TAG = "WeatherService";
    private static final long INTERVAL = 2 * 60 * 60 * 1000; // 2小时
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "WeatherService onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "WeatherService onStartCommand");
        
        // 获取天气数据
        fetchWeatherData();
        
        // 设置定时任务
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        long triggerAtTime = SystemClock.elapsedRealtime() + INTERVAL;
        Intent i = new Intent(this, WeatherService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_IMMUTABLE);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        
        return super.onStartCommand(intent, flags, startId);
    }

    private void fetchWeatherData() {
        // 使用现有的天气API获取方法
        String weatherUrl = "https://devapi.qweather.com/v7/weather/now?location=auto_ip&key=YOUR_KEY";
        
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "获取天气数据失败", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseText = response.body().string();
                NowWeather nowWeather = new Gson().fromJson(responseText, NowWeather.class);
                
                // 缓存数据到SharedPreferences
                SharedPreferences.Editor editor = getSharedPreferences("weather_data", MODE_PRIVATE).edit();
                editor.putString("weather", responseText);
                editor.apply();
                
                Log.d(TAG, "天气数据已更新并缓存");
            }
        });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}